<template>
  <div class="divSize" style="margin-top: 10%">
    <el-form
      ref="intvRuleFormRef"
      :model="intvInfo"
      status-icon
      :rules="intvRules"
      label-width="80px"
      label-position="right"
      :inline="true">
      <h1 style="font-size: 26px; text-align: center">
        预约面试<el-button style="margin-left: 10px" type="danger" size="small" @click="Reset"
          >重置</el-button
        >
      </h1>
      <br />
      <div style="margin-left: 35%; margin-bottom: 20%">
        <h1>请选择你的面试时间:</h1>
        <br />
        <el-form-item prop="intvDate">
          <el-date-picker
            :disabled="intvDisabled"
            v-model="intvInfo.intvDate"
            placeholder="请选择"
            @change="updateTimeRange"
            style="width: 350px"
            :disabled-date="intvDisabledDateFun"
          /> </el-form-item
        ><br />
        <el-form-item prop="intvTime">
          <el-time-select
            v-model="intvInfo.intvTime"
            :disabled="intvDisabled"
            style="width: 350px"
            :start="currentStartTime"
            step="00:10"
            :end="currentEndTime"
            placeholder="选择时间"
            format="HH:mm:ss"
          >
          </el-time-select>
        </el-form-item>
        <el-form-item>
          <span style="font-size: 16px; color: #545c64">面试状态: &nbsp;&nbsp;</span>
          <span v-if="intvInfo.intvState === '未面试'" style="color: #e6a23c">{{
            intvInfo.intvState
          }}</span>
          <span v-if="intvInfo.intvState === '已面试'" style="color: #409eff">{{
            intvInfo.intvState
          }}</span>
          <span v-else-if="intvInfo.intvState === '未通过'" style="color: #f56c6c">{{
            intvInfo.intvState
          }}</span>
          <span v-else-if="intvInfo.intvState === '已通过'" style="color: #67c23a">{{
            intvInfo.intvState
          }}</span>
        </el-form-item><br />

        <el-form-item>
          <el-button type="warning" @click="cancer">{{ cancerButton }}</el-button>
          <span style="margin-left: 175px"></span>
          <el-button
            :disabled="intvDisabled"
            type="primary"
            @click="submitIntvForm(intvRuleFormRef)"
            >预约面试</el-button
          >
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getIntvInfo, saveIntvInfo,clear } from '@/apis/bookInterview'
import { userStore } from '@/stores/user'
import { listTime } from '@/apis/system/time'
import Router from '@/router'
import { getExamInfo } from '@/apis/bookExam'
import { getUserInfo } from '@/apis/security/user'

const isclear=ref(true)
const userstore = userStore()
const intvRuleFormRef = ref<FormInstance>()
const intvDisabled = ref(true)
const cancerButton = ref('编辑预约')
const timeList = ref([{ value: '', disable: '' }])
const intvTime = ref([{
  startDate: '',
  endDate: '',
  startTime: '',
  endTime: ''
}])
const intvInfo = ref({
  intvId: '',
  intvDate: '',
  intvTime: '',
  intvState: '',
  intvScore: ''
})
const examInfo = ref({
  examId: '',
  examDate: '',
  examTime: '',
  examState: '',
  examScore: ''
})
const queryParams = ref({
  pageNum: 1,
  pageSize: 1000,
  eventType: '', // 修改这里，允许 eventType 为字符串或 null
  startDate: null,
  endDate: null,
  startTime: null,
  endTime: null
})
const getStudentInfo = () => {
  getUserInfo().then((res) => {
    console.log('获取学生信息')
    if (res.data.code === 200) {
      console.log('获取成功')
      userstore.userInfo = res.data.data
    } else {
      console.log('获取失败')
      ElMessage({ type: 'error', message: res.data.msg })
    }
  })
}

const getIntv = () => {
  getIntvInfo().then((res) => {
    console.log('获取预约面试信息')
    if (res.data.code === 200) {
      console.log('获取成功')
      isclear.value=false
      intvInfo.value = res.data.data
      if (intvInfo.value === null) {
        intvInfo.value = {
          intvId: '',
          intvDate: '',
          intvTime: '',
          intvState: '',
          intvScore: ''
        }
      }
      getExam()
    } else {
      console.log('获取失败')
      ElMessage({ type: 'error', message: res.data.msg })
    }
  })
}
const getExam = () => {
  getExamInfo().then((res) => {
    console.log('获取预约考试信息')
    if (res.data.code === 200) {
      console.log('获取成功')
      examInfo.value = res.data.data
      if (examInfo.value != null) {
        if (examInfo.value.examState === '未考试' || examInfo.value.examState === '') {
          ElMessageBox.alert('未参加考试无法预约面试', '提示', {
            confirmButtonText: '确定',
            callback: () => {
              Router.replace('/index')
            }
          })
        } else if (examInfo.value.examState === '已考试') {
          ElMessageBox.alert('考试结果未确定无法预约面试', '提示', {
            confirmButtonText: '确定',
            callback: () => {
              Router.replace('/index')
            }
          })
        } else if (examInfo.value.examState === '未通过') {
          ElMessageBox.alert('很遗憾，您未通过考试，无法预约面试', '提示', {
            confirmButtonText: '确定',
            callback: () => {
              Router.replace('/index')
            }
          })
        } else if (intvInfo.value.intvState === '已通过') {
          ElMessageBox.alert('恭喜您通过面试，欢迎加入卓越班', '提示', {
            confirmButtonText: '确定',
            callback: () => {}
          })
        }
      }
    } else {
      console.log('获取失败')
      ElMessage({ type: 'error', message: res.data.msg })
    }
  })
}
const currentStartTime = ref('23:59:59');
const currentEndTime = ref('00:00:00');
const updateTimeRange = () => {
  if(isclear.value){
    intvInfo.value.intvTime=''
  }
  isclear.value=true;
  const selectedDate = new Date(intvInfo.value.intvDate);
  selectedDate.setHours(0, 0, 0, 0); // 设置为当天的开始时间

  const timeRange = intvTime.value.find(time => {
    const startDate = new Date(time.startDate);
    startDate.setHours(0, 0, 0, 0); // 设置为当天的开始时间

    const endDate = new Date(time.endDate);
    endDate.setHours(0, 0, 0, 0); // 设置为当天的开始时间

    return selectedDate >= startDate && selectedDate <= endDate;
  });

  if (timeRange) {
    currentStartTime.value = timeRange.startTime;
    currentEndTime.value = timeRange.endTime;
    const now = new Date();
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String((now.getMinutes()+10)).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    const nowStr = `${hours}:${minutes}:${seconds}`
    console.log(`${hours}:${minutes}:${seconds}`);
    if(now>new Date(intvInfo.value.intvDate)){
      currentStartTime.value=nowStr
    }
  } else {
    currentStartTime.value = '23:59:59';
    currentEndTime.value = '00:00:00';
  }
};

watch(() => intvInfo.value.intvDate, updateTimeRange);
const getTime = () => {
  queryParams.value.eventType = String('面试')
  queryParams.value.pageSize = Number(1e9);
  listTime(queryParams.value).then((res) => {
    if (res.data.code === 200) {
      intvTime.value = res.data.data.records
    } else {
      ElMessage.error(res.data.msg)
    }
  })
}
onMounted(() => {
  intvDisabled.value = true
  getIntv()
  getTime()
  userstore.defaultUrl = '/BookInterview'
})
const Reset = () => {
  ElMessageBox.alert('重置后将从后台清除该面试所有信息，包括分数与状态，请谨慎', '危险', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    showCancelButton: true,
    type: 'warning'
  })
    .then(() => {
      clear().then((res) => {
        if (res.data.code === 200) {
          ElMessage({ type: 'success', message: '操作成功' })
          getIntv()
        } else {
          ElMessage({ type: 'error', message: res.data.msg })
        }
      })
    })
    .catch(() => {})
}
const intvRules = reactive<FormRules<typeof intvInfo>>({
  intvDate: [{ required: true, message: '请选择预约面试时间', trigger: 'blur' }],
  intvTime: [{ required: true, message: '请选择预约面试时间', trigger: 'blur' }]
})

const cancer = () => {
  intvDisabled.value = intvDisabled.value === false
  if (cancerButton.value === '取消编辑') {
    if (intvInfo.value.intvId != null && intvInfo.value.intvId != '')
      getIntvInfo().then((res) => {
        isclear.value=false
        intvInfo.value = res.data.data
      })
  }
  cancerButton.value = intvDisabled.value === false ? '取消编辑' : '编辑预约'
}

   const submitIntvForm = (formEl: FormInstance | undefined) => {
     if (!formEl) return;
     formEl.validate((valid) => {
       if (valid) {
         isclear.value = false;
         if (typeof intvInfo.value.intvDate !== 'string') {
           intvInfo.value.intvDate = Format(intvInfo.value.intvDate);
         }
         if (intvInfo.value.intvState !== '未面试' && intvInfo.value.intvState !== '') {
           ElMessage({ type: 'error', message: '面试已完成，无法再次预约面试' });
           return; // 确保返回 void
         }
         intvInfo.value.intvState = '未面试';
         saveIntvInfo(intvInfo.value).then((res) => {
           if (res.data.code === 200) {
             intvDisabled.value = true;
             cancerButton.value = '编辑预约';
             ElMessage({ type: 'success', message: '预约成功' });
             console.log('保存成功');
           } else {
             ElMessage({ type: 'error', message: res.data.msg });
             console.log('保存失败');
           }
         });
       } else {
         console.log('Error submit!');
         return; // 确保返回 void
       }
     });
   };


function Format(date:any) {
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  if (month < 10) month = '0' + month
  if (day < 10) day = '0' + day
  return year + '-' + month + '-' + day
}
const intvDisabledDateFun = (date: Date) => {
  for (const time of intvTime.value) {
    const startDate = new Date(time.startDate);
    const endDate = new Date(time.endDate);

    // 确保日期比较在同一时区进行
    const isSameDay = (d1: Date, d2: Date) =>
      d1.getFullYear() === d2.getFullYear() &&
      d1.getMonth() === d2.getMonth() &&
      d1.getDate() === d2.getDate();

    //检查 date 是否在 当前时间之后
    const currentDate = new Date();
    currentDate.setHours(0, 0, 0, 0);
    if (date < currentDate) {
      return true;
    }
    // 检查 date 是否在 startDate 和 endDate 之间
    if (isSameDay(date, startDate) || isSameDay(date, endDate) || (date > startDate && date < endDate)) {
      return false;
    }
  }
  return true;
}
</script>

<style>
.inputSize {
  width: 220px;
  height: 30px;
}
.divSize {
  margin: 15px;
}

.el-icon {
  margin-left: 8px;
  margin-right: 8px;
}
.demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-left: 8px;
  margin-right: 6px;
}
</style>
